package user

import (
	"gitee.com/lidongyooo/goblog/pkg/mail"
	"gitee.com/lidongyooo/goblog/pkg/password"
	"gitee.com/lidongyooo/goblog/pkg/strings"
	"gorm.io/gorm"
)

// BeforeCreate GORM 的模型钩子，创建模型前调用
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
	u.Password = password.Hash(u.Password)
	u.ActivationToken = strings.Rand(10)
	return
}

func (u *User) AfterCreate(tx *gorm.DB) (err error) {
	mail.SendWithTemplate("auth.confirm_email", u, u.Email, "感谢注册 Goblog 应用！请确认你的邮箱。")
	return
}

// BeforeUpdate GORM 的模型钩子，更新模型前调用
func (u *User) BeforeUpdate(tx *gorm.DB) (err error) {
	if !password.IsHashed(u.Password) {
		u.Password = password.Hash(u.Password)
	}
	return
}

